import router from './router'
import store from './store'

import NProgress from 'nprogress' // progress bar
// import '@/components/NProgress/nprogress.less' // progress bar custom style

NProgress.configure({ showSpinner: false }) // NProgress Configuration

// const whiteList = ['login'] // no redirect whitelist
// const defaultRoutePath = '/'
router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  const routers = store.getters.routers
  if (routers.length < 1) {
    store.dispatch('GenerateRoutes', { }).then(() => {
      // 动态添加可访问路由表
      router.addRoutes(store.getters.routers)
      const redirect = decodeURIComponent(from.query.redirect || to.path)

      if (to.path === redirect) {
        // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
        next({ ...to, replace: true })
      } else {
        // 跳转到目的路由
        next({ path: redirect })
      }
    })
  } else {
    choose(to.path)
    next()
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})

function choose(path) {
  /* menuID*/
  let menuId = 0
  let menuIds = [] // 这个用来存储父级id
  const getMenu = (pids, array) => {
    array.forEach(v => {
      if (v.path === path) {
        menuIds = pids.split(',')
        menuId = v.id
      }
      if (v.children) {
        let pId = ''
        if (pids != null) {
          pId = pids + ',' + v.id
        } else {
          pId = v.id
        }
        getMenu(pId, v.children)
      }
    })
  }
  getMenu(null, store.getters.routers)
  store.dispatch('setActive', [menuIds[0]])
  store.dispatch('setLeftActive', [menuId])
}
